"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交，执行自治事务，提交/回滚，另一会话中查询，执行成功
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、兼容B库预置表
    2、会话1关闭自动提交，调用包含自治事务的匿名块，主事务前执行自治事务，自治事务commit，主事务rollback
    3、开启会话2查询表数据清理环境
    4、关闭自动提交，调用包含自治事务的匿名块，主事务前执行自治事务，自治事务rollback，主事务commit
    5、统计表数据
    6、清理环境
Expect      :
    1、成功
    2、执行成功，查询2条数据，主事务回滚后查询1条数据
    3、查询1条数据 1、5
    4、执行成功，查询2条数据，自治事务插入的数据被回滚
    5、2条数据
    6、成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_autocommit_0040'
        self.db_name = 'db_autocommit_0040'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:兼容B库预置表;expect:成功-----'
        self.log.info(text1)
        preset_data = f"drop table if exists {self.tb_name};" \
                      f"create table {self.tb_name}(a int,b int);"
        preset_res = self.pri_sh.execut_db_sql(preset_data, dbname=self.db_name)
        self.log.info(preset_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, preset_res,
                      f"执行失败:{text1}")

        text2 = '-----step2:关闭自动提交，调用包含自治事务的匿名块，主事务' \
                '之前执行自治事务，自治事务commit，主事务rollback;' \
                'expect:执行成功，查询2条数据，主事务回滚后查询1条数据-----'
        self.log.info(text2)
        sql1 = f'''set autocommit to false;
        do \$\$ 
        declare
            pragma autonomous_transaction;
        begin
            insert into {self.tb_name} values(1, 5);
        end \$\$;
        insert into {self.tb_name} values(2, 3);
        select * from {self.tb_name} order by 1;
        select pg_sleep(3);
        rollback;
        select * from {self.tb_name} order by 1;'''
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql1, '', self.db_name))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1.5)

        text3 = '-----step3:开启会话2查询表数据;expect:查询1条数据 1、5-----'
        self.log.info(text3)
        sql2 = f"select * from {self.tb_name};"
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql2, '', self.db_name))
        session2.setDaemon(True)
        session2.start()
        session1.join(10)
        session2.join(10)
        res1 = session1.get_result()
        self.log.info(f'session1_results:\n {res1}')
        res2 = session2.get_result()
        self.log.info(f'session2_results:\n {res2}')
        self.assertIn('SET', res1, f"关闭自动提交失败: {text2}")
        self.assertIn(self.constant.CREATE_ANONYMOUS_BLOCK_SUCCESS_MSG, res1,
                      f"执行失败: {text2}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res1, f"执行失败:{text2}")
        self.assertIn(self.constant.ROLLBACK_MSG, res1, f"执行失败:{text2}")
        self.assertEqual(res1.count('1 | 5'), 2, f"执行失败:{text2}")
        self.assertIn('2 | 3', res1.splitlines()[6], f"执行失败:{text2}")
        self.assertIn('1 | 5', res2.splitlines()[2], f"执行失败:{text3}")
        self.assertIn('1 row', res2.splitlines()[-1], f"执行失败:{text3}")

        text4 = '-----step4:关闭自动提交，调用包含自治事务的匿名块，主事务' \
                '之前执行自治事务，自治事务rollback，主事务commit;' \
                'expect:执行成功，查询2条数据，自治事务插入的数据被回滚-----'
        self.log.info(text4)
        sql = f'''set autocommit to false;
        do \$\$ 
        declare
            pragma autonomous_transaction;
        begin
            insert into {self.tb_name} values(5, 5);
            rollback;
        end \$\$;
        insert into {self.tb_name} values(6, 6);
        select * from {self.tb_name} order by 1;
        commit;'''
        res = self.pri_sh.execut_db_sql(sql, '', self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.CREATE_ANONYMOUS_BLOCK_SUCCESS_MSG, res,
                      f"执行失败: {text4}")
        self.assertIn(self.constant.INSERT_SUCCESS_MSG, res, f"执行失败:{text4}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, res, f"执行失败:{text4}")
        self.assertNotIn('5 | 5', res, f"执行失败:{text4}")
        self.assertIn('6 | 6', res.splitlines()[6], f"执行失败:{text4}")

        text5 = '-----step5:统计表数据;expect:2条数据-----'
        self.log.info(text5)
        res = self.pri_sh.execut_db_sql(
            f"select count(*) from {self.tb_name};", dbname=self.db_name)
        self.log.info(res)
        self.assertEqual(res.splitlines()[2].strip(), '2', f"执行失败: {text5}")

    def tearDown(self):
        text6 = '-----step6:清理环境 expect:成功-----'
        self.log.info(text6)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text6}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
